# -*- coding: UTF-8 -*-
import logging
import os
from logging import handlers

import colorlog

from utils.constant_pool import FileUrl


class Mylogger:

    def __init__(self,log_name):
        # 1.指明日志记录到哪个文件 "F:/xxx/xx" + "info.log"
        path = FileUrl.Logs_Url.value
        if not os.path.exists(path):
            os.makedirs(path)
        logfile = f"{path}\\{log_name}"

        '''logger实例'''
        self.logger = logging.getLogger(log_name)
        '''防止日志打印2次'''
        self.logger.propagate = 0
        '''避免重复打印日志'''
        self.logger.handlers = []
        '''设置日志级别 （critical > error > warning > info > debug）'''
        self.logger.setLevel(logging.INFO)

        '''日志格式化'''
        console_fmt = "%(log_color)s[%(levelname)s][%(asctime)s]%(threadName)s-(%(module)s.%(funcName)s:%(lineno)d): %(message)s"
        file_fmt = "[%(levelname)s][%(asctime)s]%(threadName)s-(%(module)s.%(funcName)s:%(lineno)d): %(message)s"

        '''控制台输出不同级别日志颜色设置'''
        color_config = {
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'purple',
        }

        console_formatter = colorlog.ColoredFormatter(fmt=console_fmt,log_colors=color_config)
        file_formatter = logging.Formatter(fmt=file_fmt)

        '''输出到控制台'''
        console_handler = logging.StreamHandler()
        '''输出到文件 # 设置日志回滚  # 单个日志文件最大为10*1024*1024(10M),最多保存3份日志文件(除了当前写入的文件外),日志文件编码格式为utf-8'''
        file_handler = handlers.RotatingFileHandler(logfile, maxBytes=10*1024*1024, backupCount=5, encoding='utf-8')

        '''设置日志格式'''
        console_handler.setFormatter(console_formatter)
        file_handler.setFormatter(file_formatter)

        '''配置日志处理器'''
        self.logger.addHandler(console_handler)
        self.logger.addHandler(file_handler)
        self.logger.warning(f"日志路径:{logfile}")

    # 设置方法返回looger实例
    def get_logger(self):
        return self.logger
